package megrez.common.core.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.experimental.UtilityClass;

/**
 * 字符串工具
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class StringHelper {
    public static final String EMPTY = "";

    private static final String ALPHA_NUM_Str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789";
    private static final Random RANDOM = new SecureRandom();

    /**
     * 驼峰转换成下划线
     * Convert aStringUnderscored into A_STRING_UNDERSCORED.
     * 
     * @param camelCaseString the string to convert
     * 
     * @return the underscored string
     */
    public String camelCaseToUnderscore(final String camelCaseString) {
        if (!hasText(camelCaseString)) {
            return camelCaseString;
        }
        StringBuilder sb = new StringBuilder();
        for (String camelPart : camelCaseString.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
            if (sb.length() > 0) {
                sb.append("_");
            }
            sb.append(camelPart.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 字符串的字节真实长度
     * 
     * @param s
     * @return
     */
    public int byteLength(String s) {
        if (!hasText(s)) {
            return 0;
        }

        return s.getBytes(StandardCharsets.UTF_8).length;  
    }

    /**
     * 限制字符串的长度
     * 
     * @param s
     * @param limitLength
     * @return
     */
    public String limitLength(String s, int limitLength) {
        if (!hasText(s)) {
            return s;
        }
        if (limitLength <= 0) {
            return "";
        }
        
        int realLen = byteLength(s);
        if (limitLength > realLen) {
            return s;
        }
        return new String(s.getBytes(), 0, limitLength, StandardCharsets.UTF_8);
    }   
    
    /**
     * 随机字符串
     * 
     * @param maxLength 最大字符串
     * @return
     */
    public String generatedRandomStr(int maxLength) {
        if (maxLength < 0) {
            throw new CommonRuntimeException("Parameter 'maxLength' must be greater than 0" );
        }

        StringBuilder s = new StringBuilder(maxLength); 
        int length = ALPHA_NUM_Str.length();
        for (int i = 0; i < maxLength; i++) { 
            int index = RANDOM.nextInt(length); 
            s.append(ALPHA_NUM_Str.charAt(index)); 
        } 
        return s.toString(); 
    }

    /**
     * 字符串转换字符集
     * 
     * @param s
     * @param charset
     * @return
     */
    public String convertChartSet(String s, Charset charset) {
        if (!hasText(s)) {
            return s;
        }

        return new String(s.getBytes(), charset);
    }

    /**
     * 存在字符
     * 
     * @param text
     * @return
     */
    public boolean hasText(String text) {
        return text != null && text.trim().length() > 0;
    }

    /**
     * 命名方式格式化字符串
     * 
     * @param template
     * @param parameters
     * @return
     */
    public String namedFormate(String template, Map<String, Object> parameters) {
        StringBuilder newTemplate = new StringBuilder(template);
        List<Object> valueList = new ArrayList<>();

        Matcher matcher = Pattern.compile("[$][{](\\w+)}").matcher(template);

        while (matcher.find()) {
            String key = matcher.group(1);

            String paramName = "${" + key + "}";
            int index = newTemplate.indexOf(paramName);
            if (index != -1) {
                newTemplate.replace(index, index + paramName.length(), "%s");
                valueList.add(parameters.get(key));
            }
        }

        return String.format(newTemplate.toString(), valueList.toArray());
    }
}
